<template>
  <div class="standard-list-container">
    <div class="page-header">
      <h2>规格管理</h2>
    </div>

    <!-- 搜索和添加按钮 -->
    <div class="search-filter">
      <el-input
        v-model="searchName"
        placeholder="请输入规格名称"
        style="width: 300px; margin-right: 10px;"
        clearable
      />
      <el-select
        v-model="searchCategory"
        placeholder="请选择所属分类"
        style="width: 200px; margin-right: 10px;"
        clearable
      >
        <el-option
          v-for="category in categories"
          :key="category.id"
          :label="category.name"
          :value="category.id"
        />
      </el-select>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
      <el-button type="primary" @click="handleAdd">新增规格</el-button>
    </div>

    <!-- 规格列表 -->
    <el-table :data="standardsList.records" style="width: 100%" v-loading="loading">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="规格ID" width="80" />
      <el-table-column prop="name" label="规格名称" width="180" />
      <el-table-column prop="categoryId" label="所属分类" width="180">
        <template #default="scope">
          {{ getCategoryName(scope.row.categoryId) }}
        </template>
      </el-table-column>
      <el-table-column prop="options" label="规格选项" width="300">
        <template #default="scope">
          <el-tag
            v-for="(option, index) in scope.row.options"
            :key="index"
            size="small"
            style="margin-right: 5px; margin-bottom: 5px;"
          >
            {{ option }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="standardsList.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
    >
      <el-form ref="standardFormRef" :model="standardForm" :rules="rules" label-width="80px">
        <el-form-item label="规格名称" prop="name">
          <el-input v-model="standardForm.name" placeholder="请输入规格名称" />
        </el-form-item>
        <el-form-item label="所属分类" prop="categoryId">
          <el-select v-model="standardForm.categoryId" placeholder="请选择所属分类">
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="规格选项" prop="options">
          <el-space direction="vertical" style="width: 100%;">
            <div v-for="(option, index) in standardForm.options" :key="index" class="option-item">
                <el-input
                  v-model="standardForm.options[index]"
                  placeholder="请输入规格选项"
                  :style="{ width: 'calc(100% - 40px)' }"
                />
              <el-button
                type="danger"
                :style="{ marginLeft: '10px' }"
                @click="handleRemoveOption(index)"
                :disabled="standardForm.options.length <= 1"
              >
                - 移除
              </el-button>
            </div>
            <el-button type="primary" @click="handleAddOption">+ 添加选项</el-button>
          </el-space>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

// 表格数据
const standardsList = ref({ records: [], total: 0 });
const categories = ref<any[]>([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);

// 搜索
const searchName = ref('');
const searchCategory = ref('');

// 对话框
const dialogVisible = ref(false);
const dialogTitle = ref('新增规格');
const standardFormRef = ref();
const standardForm = reactive({
  id: 0,
  name: '',
  categoryId: 0,
  options: ['']
});

// 表单验证
const rules = {
  name: [
    { required: true, message: '请输入规格名称', trigger: 'blur' },
    { max: 50, message: '规格名称不能超过50个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择所属分类', trigger: 'change' }
  ],
  options: [
    { required: true, message: '请至少添加一个规格选项', trigger: 'change' }
  ]
};

// 加载规格列表
const loadStandardsList = async () => {
  loading.value = true;
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      name: searchName.value || undefined,
      categoryId: searchCategory.value || undefined
    };
    const res = await axios.get('/api/standard', { params });
    if (res.data.code === 200 && res.data.data) {
      // 将options字符串转换为数组
      res.data.data.records = res.data.data.records.map((record: any) => {
        try {
          record.options = JSON.parse(record.options);
        } catch {
          record.options = [];
        }
        return record;
      });
      standardsList.value = res.data.data;
    }
  } catch (error) {
    ElMessage.error('加载规格列表失败');
    console.error('加载规格列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 加载分类列表
const loadCategories = async () => {
  try {
    const res = await axios.get('/api/category/list');
    if (res.data.code === 200 && res.data.data) {
      categories.value = res.data.data;
    }
  } catch (error) {
    ElMessage.error('加载分类列表失败');
    console.error('加载分类列表失败:', error);
  }
};

// 获取分类名称
const getCategoryName = (categoryId: number) => {
  const category = categories.value.find(item => item.id === categoryId);
  return category ? category.name : '-';
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  loadStandardsList();
};

// 重置搜索
const resetSearch = () => {
  searchName.value = '';
  searchCategory.value = '';
  currentPage.value = 1;
  loadStandardsList();
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  loadStandardsList();
};

// 当前页变化
const handleCurrentChange = (current: number) => {
  currentPage.value = current;
  loadStandardsList();
};

// 新增规格
const handleAdd = () => {
  dialogTitle.value = '新增规格';
  Object.assign(standardForm, {
    id: 0,
    name: '',
    categoryId: 0,
    options: ['']
  });
  dialogVisible.value = true;
};

// 编辑规格
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑规格';
  // 深拷贝行数据
  Object.assign(standardForm, {
    id: row.id,
    name: row.name,
    categoryId: row.categoryId,
    // 确保options是一个新的数组
    options: [...row.options]
  });
  dialogVisible.value = true;
};

// 添加规格选项
const handleAddOption = () => {
  standardForm.options.push('');
};

// 移除规格选项
const handleRemoveOption = (index: number) => {
  standardForm.options.splice(index, 1);
};

// 提交表单
const handleSubmit = async () => {
  try {
    await standardFormRef.value.validate();
    
    // 移除空的选项
    const validOptions = standardForm.options.filter((option: string) => option.trim() !== '');
    if (validOptions.length === 0) {
      ElMessage.warning('请至少添加一个非空的规格选项');
      return;
    }
    
    const formData = {
      ...standardForm,
      options: JSON.stringify(validOptions)
    };
    
    let res;
    if (standardForm.id === 0) {
      res = await axios.post('/api/standard', formData);
    } else {
      res = await axios.put('/api/standard', formData);
    }
    
    if (res.data.code === 200) {
      ElMessage.success(standardForm.id === 0 ? '新增成功' : '修改成功');
      dialogVisible.value = false;
      loadStandardsList();
    }
  } catch (error) {
    console.error('提交失败:', error);
  }
};

// 删除规格
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个规格吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const res = await axios.delete(`/api/standard?idList=${id}`);
    if (res.data.code === 200) {
      ElMessage.success('删除成功');
      loadStandardsList();
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
      console.error('删除失败:', error);
    }
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadCategories();
  loadStandardsList();
});
</script>

<style scoped>
.standard-list-container {
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.search-filter {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
</style>